package com.example.hotelback.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.hotelback.entity.Params;
import com.example.hotelback.entity.Room;
import com.example.hotelback.service.RoomService;
import com.example.hotelback.utils.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/room")
public class RoomController {

    @Autowired
    private RoomService roomService;

    @ApiOperation("查看所有房型")
    @GetMapping("/findAll")
    @ResponseBody
    public Result findAll() {
        List<Room> list = roomService.findAll();
        return Result.success(list);
    }

    /**
     * 分页查询所有房型
     * @param params
     * @return
     */
    @ApiOperation("分页查询所有房型")
    @GetMapping("/findByPage")
    @ResponseBody
    public Result findByPage(Params params) { // 传入当前页数和每页台条数；@RequestParam从Http请求中提取参数
        IPage<Room> ipage = roomService.findByPage(params);
        return Result.success(ipage);
    }

    /**
     * 按条件查房型
     * @param params
     * @return
     */
    @ApiOperation("按条件查询房型")
    @GetMapping("/findBySearch")
    @ResponseBody
    public Result findBySearch(Params params) {
        IPage<Room> iPage = roomService.findBySearch(params);
        return Result.success(iPage);
    }

    /**
     * 删除房型
     * @param params
     * @return
     */
    @ApiOperation("删除房型")
    @PostMapping("/delete")
    @ResponseBody
    public Result delete(@RequestBody Map<String, Integer> params) {
        int id = params.get("id");
        roomService.deleteRoom(id);
        return Result.success();
    }

    /**
     * 新增房型
     * @param room
     * @return
     */
    @ApiOperation("新增房型")
    @PostMapping("/add")
    @ResponseBody
    public Result add(@RequestBody Room room) {
        roomService.addRoom(room);
        return Result.success();
    }

    /**
     * 更新房型
     * @param id
     * @param newRoom
     * @return
     */
    @ApiOperation("更新房型")
    @PutMapping("/update")
    @ResponseBody
    public Result update(@RequestBody Map<String, Object> payload) {
        Integer id = (Integer) payload.get("id");
        Room newRoom = new ObjectMapper().convertValue(payload.get("newRoom"), Room.class);
        roomService.updateRoom(id, newRoom);
        return Result.success();
    }

    @ApiOperation("获取一个房型")
    @GetMapping("/getRoomInfo")
    @ResponseBody
    public Result getFilename(int id) {
        Room room = roomService.findOneRoom(id);
        return Result.success(room);
    }
}
